package com.justech.tcp.server;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import io.netty.util.internal.ThreadLocalRandom;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeoutException;

/**
 * @ClassName
 * @Author: xiaofeng.yang
 * @Date: Create in 16:11 2019/12/2
 * @Description : TODO
 * @Version: 1.0
 */
public class ConsumerConnectionFactory {
    private static final Logger logger=LoggerFactory.getLogger(ConsumerConnectionFactory.class);
    private String host;
    private int port;
    private String userName;
    private String pssword;
    private String virtualHost;
    private static ConsumerConnectionFactory consumerConnectionFactory;
    private List<Connection> connections = new ArrayList<Connection>(10);

    public static ConsumerConnectionFactory getInstance() throws IOException, TimeoutException {
        if (null == consumerConnectionFactory) {
            synchronized (ConsumerConnectionFactory.class) {
                if (null == consumerConnectionFactory) {
                    consumerConnectionFactory = new ConsumerConnectionFactory();
                }
            }
        }
        return consumerConnectionFactory;
    }

    private ConsumerConnectionFactory() throws IOException, TimeoutException {
        this.host = System.getProperty("host", "localhost");
        this.port = Integer.valueOf(System.getProperty("port", "5672"));
        this.userName = System.getProperty("user-name", "guest");
        this.pssword = System.getProperty("password", "guest");
        this.virtualHost = System.getProperty("virtual-host", "/");
        connections();
    }

    private ConnectionFactory connectionFactory() {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(this.host);
        connectionFactory.setPort(this.port);
        connectionFactory.setVirtualHost(this.virtualHost);
        connectionFactory.setUsername(this.userName);
        connectionFactory.setPassword(this.pssword);
        connectionFactory.setAutomaticRecoveryEnabled(true);
        connectionFactory.setNetworkRecoveryInterval(10000);
        return connectionFactory;
    }

    private void connections() throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = connectionFactory();
        for (int i = 0; i < 10; i++) {
            this.connections.add(connectionFactory.newConnection("mes"));
        }
        logger.info("rabbitmq connections init success!");
    }

    public Connection getConnection() {
        Random random = new Random();
        int n = ThreadLocalRandom.current().nextInt(this.connections.size()) % this.connections.size();
        return this.connections.get(n);
    }
}
